package demo;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class MySync extends AbstractQueuedSynchronizer {
    // 实现tryAcquire方法，用于获取锁
    protected boolean tryAcquire(int arg) {
        int state = getState();
        Thread currentThread = Thread.currentThread();
        if (state == 0) {
            // 如果state为0，表示当前没有线程持有锁，可以尝试获取锁
            if (compareAndSetState(0, arg)) {
                // 获取锁成功，设置当前线程为独占线程
                setExclusiveOwnerThread(currentThread);
                return true;
            }
        } else if (getExclusiveOwnerThread() == currentThread) {
            // 如果当前线程已经持有锁，可以重入
            int nextState = state + arg;
            setState(nextState);
            return true;
        }
        return false;
    }

    // 实现tryRelease方法，用于释放锁
    protected boolean tryRelease(int arg) {
        Thread currentThread = Thread.currentThread();
        if (getExclusiveOwnerThread() != currentThread) {
            throw new IllegalMonitorStateException("不是当前线程持有锁");
        }
        int state = getState() - arg;
        if (state == 0) {
            // 如果state变为0，表示当前没有线程持有锁，清空独占线程
            setExclusiveOwnerThread(null);
        }
        setState(state);
        return true;
    }
}

